﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Weber.CS3280.Interfaces;
using Weber.CS3280.UI.ViewModels;

namespace Weber.CS3280.Inventory.UI.Windows
{
	/// <summary>
	/// Interaction logic for EditControlHostWindow.xaml
	/// </summary>
	public partial class EditControlHostWindow : Window, IModalWindow
	{
		private ItemDetailViewModelBase _viewModel;
		private bool _isModal;

		public EditControlHostWindow()
		{
			InitializeComponent();
		}

		protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
		{
			ICustomCleanup cleanup = DataContext as ICustomCleanup;

			if (cleanup != null)
				cleanup.DoCleanup();

			base.OnClosing(e);
		}

		public static void ShowWindow<T>(ItemDetailViewModelBase viewModel, Window owner) where T : Control, new()
		{
			EditControlHostWindow window = new EditControlHostWindow();
			// Create the hosted control
			T editableControl = new T();

			window.InitializeHostWindow(editableControl, viewModel);
			window.Owner = owner;
			window.Show();
		}

		public static bool ShowModal<T>(ItemDetailViewModelBase viewModel, Window owner) where T : Control, new()
		{
			EditControlHostWindow window = new EditControlHostWindow();
			T editableControl = new T();

			window.InitializeHostWindow(editableControl, viewModel);
			window.Owner = owner;
			window._isModal = true;
			return window.ShowDialog() ?? false;
		}

		private void InitializeHostWindow(Control editableControl, ItemDetailViewModelBase viewModel)
		{
			_viewModel = viewModel;
			// Insert the Control into the Grid
			gridControlHost.Children.Insert(0, editableControl);
			// Set the attached properties of the control to make sure it's in the right position
			editableControl.SetValue(Grid.RowProperty, 0);
			editableControl.SetValue(Grid.ColumnProperty, 0);

			DataContext = viewModel;
		}

		private void btnCancel_Click(object sender, RoutedEventArgs e)
		{
			// If this Window is Modal, then set the DialogResult to false
			if (_isModal)
				DialogResult = false;

			// Close the window, throwing away any changes
			Close();
		}

		public bool IsModal
		{
			get { return _isModal; }
		}
	}
}
